package co.infinum.goldfinger.example;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.utils.TextTool;

/**
 * ex.
 *
 * @author zh
 * @since 2021-06-25
 */
public class SetPinAbility extends Ability {
    private TextField pinInputView;
    private Component setPinButton;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        String pin = SharedPrefs.getPin();
        if ("".equals(pin)) {
            super.setUIContent(ResourceTable.Layout_ability_set_pin);
            initViews();
            initListeners();
        } else {
            navigateToLogin();
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
        updateSetPinState();
    }

    private void initListeners() {
        pinInputView.addTextObserver(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(String text) {
                if (TextTool.isNullOrEmpty(text)) {
                    return;
                }
                String newStr = text;
                newStr = newStr.replaceAll("[^0-9]", "");
                if (text.length() > 4) {
                    newStr = text.substring(0, 4);
                }
                pinInputView.setText(newStr);
                updateSetPinState();
            }
        });
        setPinButton.setClickedListener(v -> {
            SharedPrefs.setPin(pinInputView.getText().toString());
            navigateToLogin();
        });
    }

    private void initViews() {
        pinInputView = (TextField) findComponentById(ResourceTable.Id_pinInputView);
        setPinButton = findComponentById(ResourceTable.Id_setPinButton);
    }

    private void navigateToLogin() {
        Class<?> cls = SharedPrefs.isRxExample() ? RxLoginAbility.class : LoginAbility.class;
        Intent intent = new Intent();
        // 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("co.infinum.goldfinger.example")
                .withAbilityName(cls.getName())
                .build();
        // 把operation设置到intent中
        intent.setOperation(operation);
        startAbility(intent);
        terminateAbility();
    }

    private void updateSetPinState() {
        setPinButton.setEnabled(pinInputView.getText().toString().length() == 4);
    }
}
